package cn.tedu._07springaop.aop;

import ch.qos.logback.classic.spi.EventArgUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class logaspect
{



    //定义一个类中具体切点
    //@Pointcut(value="execution(public int cn.tedu._07springaop.aop.calculatorimpl.add(..))")
    //定义一个类中多个切点
    //@Pointcut(value="execution(public int cn.tedu._07springaop.aop.calculatorimpl.add(..)
    //||execution(cn.tedu._07springaop.aop.calculatorimpl.sub(..))")
    //定义所有类中所有方法切点
    //@Pointcut(value="execution(* * ..*.*(..))")
    //定义一个类中所有切点
//    @Pointcut(value="execution(public int cn.tedu._07springaop.aop.calculatorimpl.*(..))")
//    @Pointcut(value="bean(calculatorimpl)")//匹配指定bean名称的类
    @Pointcut(value="within(cn.tedu._07springaop.aop.calculatorimpl)")//匹配包名.类名下的类
    public void pointcut(){}

    @Before(value="pointcut()")
    public void beforemethod(JoinPoint joinPoint)
    {
        String name = joinPoint.getSignature().getName();
        String arg= Arrays.toString(joinPoint.getArgs());
        System.out.println(name+"开始，参数为"+arg);
    }

    @After(value="pointcut()")
    public void aftermethod(JoinPoint joinPoint)
    {
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"结束");
    }

    @AfterReturning(value="pointcut()",returning = "result")
    public void afterreturning(JoinPoint joinPoint,Object  result)
    {
        String name = joinPoint.getSignature().getName();

        System.out.println(name+"正常返回，结果为"+result);
    }

    @AfterThrowing(value="pointcut()",throwing = "ex")
    public void afterthrowing(JoinPoint joinPoint,Throwable ex)
    {
        String name = joinPoint.getSignature().getName();

        System.out.println(name+"异常返回，异常为"+ex.getMessage());
    }

    @Around(value="pointcut()")
    public Object around(ProceedingJoinPoint joinPoint)
    {
        Object result = null;
        System.out.println("环绕开始");
        try
        {
            System.out.println("方法执行前");
            result=joinPoint.proceed();
            System.out.println("返回");
        }catch(Throwable ex){
            System.out.println("异常");
        }finally {
            System.out.println("方法执行后");
        }
        return result;
    }

}
